package com.le.basic.Sort;


import org.junit.Test;

import java.util.Arrays;

public class HeapSortedTest {
    public static void testHeapSorted(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            // 建立大根堆
            heapInsert(arr, i);
        }
        int size = arr.length;
        swap(arr, 0, --size); // 交换收尾元素
        while (size > 0){
            heapify( arr,0,size);
            swap(arr,0,--size);
        }
    }

    public static void heapify(int[] arr, int i, int size){
        int left = i * 2 + 1;
        while (left < size){
            int maxIndex = left + 1 < size && arr[left] < arr[left + 1] ? left + 1 : left;
            maxIndex = arr[maxIndex] < arr[i] ? i : maxIndex;
            if (maxIndex == i){
                break;
            }
            swap(arr,maxIndex,i);
            i = maxIndex;
            left = left * 2 + 1;
        }
    }

    public static void heapInsert(int[] arr, int index) {
        while (arr[index] > arr[(index - 1) / 2]) {
            swap(arr, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static int[] generateArray(int num) {
        int[] arr = new int[num];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 10) - 5;
        }
        return arr;
    }

    @Test
    public void test(){
        int[] ints = generateArray(10);
        System.out.println(Arrays.toString(ints));
        testHeapSorted(ints);
        System.out.println(Arrays.toString(ints));
    }
}
